;( function () {
    "use strict";
   	var param_map = Result.getLocationParamObject();
    var race_id = param_map.race_id;
    var quCode = null;
    var global_param_map;
    var raceInfo = null;
    
	 $( function () {
		App.init();
		$("#head_login_status").empty();
		if(!App.checkLogin()){
			global_param_map = {};
			$("#head_login_status").append($("#un_login_template"));
		} else {
			global_param_map = App.getCookeData();
			$("#_user_name").html(global_param_map["nickname"]);
			if(global_param_map["user_icon"] !== undefined && global_param_map["user_icon"] != null 
					&& global_param_map["user_icon"] != ""){
					$("#_head_pic").attr("src", Interface.image.pre + global_param_map["user_icon"]);
				 }			
			$("#head_login_status").append($("#already_login_template"));
		}
		 
		 loadByIp();
		 //定位的
		 var cityJson = App.getCity();
		 if(cityJson){
			 $("#local_city").attr("org_code", cityJson.org_code);
			 $("#local_city").attr("org_name", cityJson.org_name);
			 $("#local_city").find("a").html(cityJson.org_name);
			 $("#local_city").removeClass("yes").addClass("yes");
		 } else {
			 $("#local_city").find("a").html("没定位到城市");
			 $("#local_city").removeClass("yes");
		 }
		 //用户正在用的cit
		 var useCityJson = App.getUseCity();
		 if(useCityJson){
			 quCode = useCityJson.org_code;
			 $("#chengshi").html(useCityJson.org_name);
		 }
		 loadAllCity();
		 if(useCityJson){
			 $(".citylist li.yes").removeClass("active");
			 var len = $(".citylist").find("li[org_code="+quCode+"]").length;
			 if(len == 1){
				 $(".citylist li.yes[org_code='"+quCode+"']").removeClass("active").addClass("active");
			 } else if (len > 1) {
				 $(".citylist li.yes[org_code='"+quCode+"']").eq(0).removeClass("active").addClass("active");
			 }
		 }
		 
		 
		 loadDetail();
		 $("#cat_name").html(raceInfo.matchType.name);
		 $("#to_race_index").click(function(){
			 Result.forward("raceIndex.html", {"category_id" : raceInfo.matchType.id});
		 });
	 });
	 
	 
	 $("#city-modal").on("focus", "#search_city", function(){
		 var that = $(this);
		 Result.doResult( {
	    	url: Interface.zs.orgGetOrgList,
	       	type: "POST",
	       	async: false,
	       	data : {}
	   	}, function ( data) {
	   		that.autocomplete(data , {  
	   			minChars: 0,
	   	        width: 680,
	   	        autoFill: false,
	            matchContains: true,  
	            highlight : false,
	            scroll : true, // 当结果集大于默认高度时是否使用卷轴显示  
	            formatItem: function(row, i, max) {  
	                 return row.org_name;  
	            },  
	            formatMatch: function(row, i, max) {  
	                 return row.org_name;  
	            },  
	            formatResult: function(row) {
	                return row.org_name;  
	            }  
	        }).result(function(event, row, formatted) {
	        	$(".citylist li.yes").removeClass("active");
	        	quCode = row.org_code;
            	var org_name = row.org_name;
				$("#chengshi").html(org_name);
				$("#city-modal").modal("close");
				//选择完更新缓存
				var jj = {"org_code" : quCode, "org_name" : org_name};
  			  	App.setUseCity(jj);
				var len = $(".citylist").find("li[org_code="+quCode+"]").length;
				 if(len == 1){
					 $(".citylist li.yes[org_code='"+quCode+"']").removeClass("active").addClass("active");
				 } else if (len > 1) {
					 $(".citylist li.yes[org_code='"+quCode+"']").eq(0).removeClass("active").addClass("active");
				 }
            });  
	   	}, function ( desc ) {
	        Result.alert( "对不起:" + desc );
	    }, function ( err ) {
	        Result.alert( "错误:" + JSON.stringify(err));
	    } );
	 });
	 
	 
	 
	 function loadAllCity(){
		var $list = $("#all_city_list"),
			$template = $("#all_city_template");
			$("#host_city").empty();
		Result.doResult( {
        	url: Interface.zs.orgGetOrgList,
           	type: "POST",
           	async: false,
           	data : {}
       	}, function ( data) {
	       	var letterMap = {
	       		"A" : [], "B" : [], "C" : [], "D" :[],  "E" : [], "F" : [], "G" : [], "H" : [],
	       		"I" : [], "J" : [], "K" : [], "L" : [], "M" : [], "N" : [], "O" : [],
	       		"P" : [], "Q" : [], "R" : [], "S" : [], "T" : [], "U" : [], "V" : [],
	       		"W" : [], "X" : [], "Y" : [], "Z" : []
	       	};
	       	if( $.isArray( data ) ) {
	    		for( var i = 0, l = data.length; i < l; i++ ) {
	    			var temp = data[i]["first_letter"].toUpperCase();
	    			letterMap[temp].push(data[i]);
	            }
	    	   for(var i in letterMap){
	    		  var letterList = letterMap[i];
	    		  if(letterList.length == 0){
	    			  continue;
	    		  }
	    		  var obj = $template.clone().removeAttr( "id" );
	    		  obj.find(".letter_fist").html(i);
	    		  obj.find(".citylist").empty();
	    		  for( var j = 0, l = letterList.length; j < l; j++ ) {
	    			  var org_name = letterList[j]['org_name'];
	    			  //填补hot
	    			  if(letterList[j]['is_hot'] == 1){
	    				  var ah = '<li class="yes '+active+'" org_code="'+letterList[j]['org_code']+'" org_name="'+org_name+'"><a >'
		    			  	+org_name+'</a></li>';
	    				  $("#host_city").append(ah);
	    			  }
	    			  
	    			  //当定位没有订到的话，默认一个已开通的城市
	    			  var active = "";
	    			  if(quCode == null || quCode == ""){
	    				  $("#chengshi").html(org_name);
		    			  quCode = letterList[j]['org_code'];
		    			  active = "active";
		    			  //设置默认的缓存
		    			  var jj = {"org_code" : quCode, "org_name" : org_name};
		    			  App.setUseCity(jj);
		    		  }
	    			  var a = '<li class="yes '+active+'" org_code="'+letterList[j]['org_code']+'" org_name="'+org_name+'"><a >'
	    			  	+org_name+'</a></li>';
	    			  obj.find(".citylist").append(a);
	    			  
		          }
	    		  $list.append(obj);
	    	   }
	        }
	       	
	        $(".citylist li.yes").off().click(function(){
		       	 $(".citylist li.yes").removeClass("active");
		       	 $(this).addClass("active");
	        });
	       	
			$("#btn-city-center").on("click",function(){
				var active =  $(".citylist li.active"),
					name = active.attr("org_name"),
					code = active.attr("org_code");
				quCode = code;
				$("#chengshi").html(name);
				$("#city-modal").modal("close");
				//选择完更新缓存
				var jj = {"org_code" : quCode, "org_name" : name};
  			  	App.setUseCity(jj);
			});
	       	
       	}, function ( desc ) {
            Result.alert( "对不起:" + desc );
        }, function ( err ) {
            Result.alert( "错误:" + JSON.stringify(err));
        } );
	 }
	 
	 
	 function loadDetail(){
		 Result.doResult( {
			 url:  Interface.zs.matchGetMatchDetail,
			 data: {"match_id" : race_id, "user_id" : (global_param_map['id'] !== undefined && global_param_map['id'] != null 
 	      			&& global_param_map['id'] != '') ? global_param_map['id'] : 0},
			 type: "POST",
			 async: false,
		 }, function ( data ) {
			 raceInfo = data;
			 Result.fillData( $("#tab1"), data, "field" );
			 var contentList = data.descList;
			 var $content_template = $("#content_template");
			 $("#tab1").find(".desc_list").empty();
			 if( $.isArray( contentList ) ) {
          		for( var i = 0, l = contentList.length; i < l; i++ ) {
          			var obj = $content_template.clone().removeAttr( "id" );
          			$("#tab1").find(".desc_list").append( Result.fillData( obj, contentList[i], "field" ));
                 }
              }
			 
			 $("#cansai").html(data.real_reg_num + "/" +data.can_reg_num);
			  
			 var userList = data.userList;
			 $("#user_list").empty();
			 if( $.isArray( userList ) ) {
          		for( var i = 0, l = userList.length; i < l; i++ ) {
          			var obj = $("#user_template").clone().removeAttr( "id" );
          			$("#user_list").append( Result.fillData(obj , userList[i], "field" ));
                 }
              }
			 
			 $("#bg_icon").attr("src", Interface.image.pre + data.matchType.detail_icon);
			 $("#iconimg100").attr("src", Interface.image.pre + data.matchType.match_icon);
			 $("#xiangmu_soan").html(data.matchType.name);
			 
			 if(data.matchStatus == 1){
				 $("#timeline").find("div.status").eq(0).addClass("start");
				 $("#timeline").find("div.status").eq(1).addClass("nostart");
				 $("#timeline").find("div.status").eq(2).addClass("nostart");
				 $("#timeline").find("div.status").eq(3).addClass("nostart");
			 } else if (data.matchStatus == 2 || data.matchStatus == 3) {
				 $("#timeline").find("div.status").eq(0).addClass("hasover");
				 $("#timeline").find("div.status").eq(1).addClass("start");
				 $("#timeline").find("div.status").eq(2).addClass("nostart");
				 $("#timeline").find("div.status").eq(3).addClass("nostart");
			 } else if (data.matchStatus == 4){
				 $("#timeline").find("div.status").eq(0).addClass("hasover");
				 $("#timeline").find("div.status").eq(1).addClass("hasover");
				 $("#timeline").find("div.status").eq(2).addClass("start");
				 $("#timeline").find("div.status").eq(3).addClass("nostart");
			 } else if (data.matchStatus == 5){
				 $("#timeline").find("div.status").eq(0).addClass("hasover");
				 $("#timeline").find("div.status").eq(1).addClass("hasover");
				 $("#timeline").find("div.status").eq(2).addClass("hasover");
				 $("#timeline").find("div.status").eq(3).addClass("start");
			 }
			 
			 if(data.collect == 1){
				 $(".icon-collect").removeClass("cur").addClass("cur");
			 } else {
				 $(".icon-collect").removeClass("cur");
			 }
			 
			 
		 }, function ( desc ) {
	       Result.alert( "对不起:" + desc );
		 }, function ( err ) {
			 Result.alert( "错误:" + JSON.stringify(err));
		 } );
	 }
	 
	 $("#tab1").on("click", ".woyapbaobutton", function(){
		 if(global_param_map['id'] == undefined || global_param_map['id'] == null 
	     			|| global_param_map['id'] == ''){
			 alert("您还未登录");
			 return;
		 }
		 Result.forward("baoming.html", {"race_id" : param_map.race_id});
	 });
	 
	 
	 $(".icon-collect").on("click", function () {
		 if(global_param_map['id'] == undefined || global_param_map['id'] == null 
	     			|| global_param_map['id'] == ''){
			 alert("您还未登录");
			 return;
		 }
		 var params= {
		     "user_id" : global_param_map['id'],
		     "type" : 3,
		     "foreign_id" : race_id,
		     "action_type" : 1
		 };
		 var that = $(this);
		 if($(this).hasClass("cur")){
			 Result.doResult( {
				 url:   Interface.zs.userDelAction,
				 data: params,
				 type: "POST",
				 async: false,
			 }, function ( data ) {
				 alert("已取消收藏!");
				 that.removeClass("cur");
			 }, function ( desc ) {
		       Result.alert( "对不起:" + desc );
			 }, function ( err ) {
				 Result.alert( "错误:" + JSON.stringify(err));
			 } );
			 
         } else {
			 Result.doResult( {
				 url:   Interface.zs.userAddAction,
				 data: params,
				 type: "POST",
				 async: false,
			 }, function ( data ) {
				 alert("收藏成功!");
				 that.removeClass("cur").addClass("cur");
			 }, function ( desc ) {
		       Result.alert( "对不起:" + desc );
			 }, function ( err ) {
				 Result.alert( "错误:" + JSON.stringify(err));
			 } );
         }
     });
	 
	 
	 
	 window.replaceLogo = function ( $field, logo, rowVal ) {
		$field.attr("src", Interface.image.pre + rowVal['userIcon']);
	 };
	 
	 window.replaceuserIcon = function ( $field, logo, rowVal ) {
		 var icon = rowVal['userIcon'];
		 if(icon != null && icon != ""){
			 $field.attr("src", Interface.image.pre + icon);
		 } else {
			 $field.attr("src", "../../imgs/icons/sy_73.png");
		 }
		
	 };
	 
	 
	 window.replaceBaoButton = function ( $field, matchStatus, rowVal ) {
		 var status = rowVal['matchStatus'];
		 if(status == 2){
			$field.html("我要报名");
			$field.addClass("woyapbaobutton");
			$field.parent().addClass("baoming-baoming");
			$field.parent().removeClass("baom");
		 } else if (status == 1){
			$field.html("等待报名");
		 } else if (status == 3){
			$field.html("已报名");
		 } else if (status == 4){
			$field.html("报名结束");
		 } else {
			$field.html("已比赛");
		 }
	 };
	 
	 window.replaceRegFee = function ( $field, fee, rowVal ) {
		if(fee == null || fee == 0 || fee == ""){
		} else {
			$field.html("&yen;" + fee);
		}
	 };
	 window.replaceRefereeMode = function ( $field, mode, rowVal ) {
		 if(mode == 1){
			 $field.html("自裁模式");
		 } else {
			 $field.html("裁判模式");
		 }
	 };
	 
	 window.replaceRiqi = function ( $field, time, rowVal ) {
		 var startDatetimeArray = time.split(" ");
		 var startArr = startDatetimeArray[0].split("-");
		 var startMonth = parseInt(startArr[1]);
		 var day = parseInt(startArr[2]);
		 $field.html(startMonth + "." + day);
	 };
	 
	 
	 
		 
	
}( window ) );
